import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Alert,
  SafeAreaView,
  Animated,
} from 'react-native'
import {
  BarCodeScanningResult,
  Camera,
  CameraType,
  FlashMode,
} from 'expo-camera'
import { useEffect, useRef, useState } from 'react'
import * as FileSystem from 'expo-file-system'
import * as MediaLibrary from 'expo-media-library'
import { StackProps } from '@/routes/type'
import { LinearGradient } from 'expo-linear-gradient'
import { Easing } from 'react-native-reanimated'

const CameraView: React.FC<StackProps<'Camera'>> = props => {
  const [type, setType] = useState(CameraType.back) // 摄像头前置/后置
  const [flash, setFlash] = useState<FlashMode>(FlashMode.off)
  const [cameraReady, setCameraReady] = useState(false) // 摄像机是否已就绪
  const cameraRef = useRef<Camera>(null)
  const [permission, requestPermission] = Camera.useCameraPermissions() // 权限
  const animValue = useRef(new Animated.Value(0)).current

  useEffect(() => {
    const animation = Animated.loop(
      Animated.timing(animValue, {
        toValue: 1,
        duration: 2000,
        useNativeDriver: true,
        easing: Easing.linear,
      }),
    )
    animation.start()
    return () => animation.stop()
  }, [])
  const translateY = animValue.interpolate({
    inputRange: [0, 1],
    outputRange: [-80, 400],
  })
  if (!permission) {
    // Camera permissions are still loading
    return <View />
  }

  if (!permission.granted) {
    // Camera permissions are not granted yet
    Alert.alert('系统提示', 'ChildApp想请求您的系统摄像机', [
      { text: '确定', style: 'default', onPress: requestPermission },
    ])

    return <View style={styles.container} />
  }

  function toggleCameraType() {
    if (!cameraReady) {
      return
    }
    setType(current =>
      current === CameraType.back ? CameraType.front : CameraType.back,
    )
  }
  function onLight() {
    if (!cameraReady) {
      return
    }
    setFlash(val => (FlashMode.torch === val ? FlashMode.off : FlashMode.torch))
  }
  async function takePhoto() {
    if (!cameraReady) {
      return
    }
    const photo = await cameraRef?.current?.takePictureAsync({
      exif: true,
      quality: 1,
    })
    if (!photo) {
      return
    }
    const fileName = `owl_${Date.now()}_${Math.random().toFixed(5)}.jpg`
    const destination = `${FileSystem.documentDirectory}${fileName}`
    try {
      await FileSystem.copyAsync({
        from: photo.uri,
        to: destination,
      })

      await MediaLibrary.saveToLibraryAsync(destination)
    } catch (e) {
      console.log(e)
    }
  }
  function onCameraReady() {
    setCameraReady(true)
  }
  function onBarCodeScanned(scanningResult: BarCodeScanningResult) {
    console.log(scanningResult, 'scanningResult')
  }
  function goBack() {
    props.navigation.goBack()
  }
  return (
    <View style={styles.container}>
      <Camera
        ref={cameraRef}
        style={styles.camera}
        type={type}
        flashMode={flash}
        onCameraReady={onCameraReady}
        onBarCodeScanned={onBarCodeScanned}
      >
        <SafeAreaView style={styles.areaView}>
          <TouchableOpacity
            activeOpacity={0.8}
            style={styles.backIconWrap}
            onPress={goBack}
          >
            <Text style={styles.backIcon}>&#xe601;</Text>
          </TouchableOpacity>
          <View style={styles.lightMvBox}>
            <Animated.View
              style={[
                styles.lightMv,
                {
                  transform: [{ translateY }],
                },
              ]}
            >
              <LinearGradient
                colors={['transparent', '#f394a5']}
                start={{ x: 0.5, y: 0.5 }}
                end={{ x: 0.5, y: 1 }}
                style={styles.tail}
              />
            </Animated.View>
          </View>
          <View style={styles.buttonContainer}>
            <TouchableOpacity
              activeOpacity={0.8}
              style={styles.button}
              onPress={onLight}
            >
              <Text style={styles.text}>&#x10193;</Text>
            </TouchableOpacity>
            <TouchableOpacity
              activeOpacity={0.8}
              style={[styles.button, styles.middleBtn]}
              onPress={takePhoto}
            >
              <Text style={[styles.text, styles.middleTxt]}>&#xe61f;</Text>
            </TouchableOpacity>
            <TouchableOpacity
              activeOpacity={0.8}
              style={styles.button}
              onPress={toggleCameraType}
            >
              <Text style={styles.text}>&#xe672;</Text>
            </TouchableOpacity>
          </View>
        </SafeAreaView>

        <View style={styles.pointBox}>
          <View style={styles.point}>
            <Text style={styles.pIcon}>&#xe615;</Text>
          </View>
        </View>
      </Camera>
    </View>
  )
}
export default CameraView
const styles = StyleSheet.create({
  backIconWrap: {
    width: 40,
    height: 40,
    left: 12,
    top: 12,
    backgroundColor: '#fff',
    borderRadius: 20,
    display: 'flex',
    alignContent: 'flex-start',
  },
  backIcon: {
    lineHeight: 40,
    fontFamily: 'iconfont',
    textAlign: 'center',
    fontSize: 16,
  },
  container: {
    flex: 1,
    backgroundColor: '#000',
    justifyContent: 'center',
    fontFamily: 'iconfont',
  },
  camera: {
    flex: 1,
    position: 'relative',
  },
  areaView: {
    flex: 1,
    height: '100%',
    display: 'flex',
    justifyContent: 'space-between',
  },
  buttonContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    display: 'flex',
    margin: 32,
    alignItems: 'flex-end',
  },
  button: {
    borderRadius: 19,
    backgroundColor: '#f1f1f1',
    width: 38,
    height: 38,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
  },
  middleBtn: {
    width: 58,
    height: 58,
    borderRadius: 29,
    backgroundColor: '#f394a5',
  },
  middleTxt: {
    fontSize: 36,
    color: '#fff',
  },
  text: {
    fontSize: 22,
    color: '#282828',
    borderRadius: 19,
    fontFamily: 'iconfont',
  },
  lightMvBox: {
    height: 360,
    width: '100%',
    display: 'flex',
    alignItems: 'center',
    overflow: 'hidden',
  },
  lightMv: {
    width: '80%',
    height: 80,
  },
  tail: {
    height: 80,
    width: '100%',
    backgroundColor: 'transparent',
    borderBottomLeftRadius: 12,
    borderBottomRightRadius: 12,
  },
  pointBox: {
    position: 'absolute',
    width: '100%',
    height: '100%',
  },
  point: {
    width: 24,
    height: 24,
    backgroundColor: '#f394a5',
    borderRadius: 12,
  },
  pIcon: {
    fontFamily: 'iconfont',
    fontSize: 16,
    color: '#fff',
    textAlign: 'center',
    lineHeight: 24,
  },
})
